<template>
  <a-tree-select
    v-model="deptId"
    v-bind="attrs"
    :labelInValue="true"
    allowClear
    show-search
    :tree-data="dataSource"
    :dropdown-style="{ maxHeight: '300px', overflow: 'auto' }"
    :getPopupContainer="getPopupContainerFn"
    :replaceFields="replaceFields"
    treeNodeFilterProp="title"
    @change="handleChange"
  >
  </a-tree-select>
</template>

<script>

import { TreeSelect as ATreeSelect } from 'ant-design-vue'
import { deptEnableTree } from '@/services/system'
export default {
  name: 'ZSelectDept',
  components: { ATreeSelect },
  props: {
    value: [String, Array],
    getPopupContainer: {
      type: Function,
      default: () => document.body
      // default: (node) => node.parentNode
    },
    popupContainer: String // 自定义属性，方便设置下拉框popupContainer属性 body|parent
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  data() {
    return {
      replaceFields: {
        children: 'children',
        title: 'deptName',
        value: 'deptCode'
      },
      dataSource: [],
      default: {
        maxTagCount: 2,
        treeCheckStrictly: true
      },
      deptId: '',
      deptObj: {},
      deptInit: false
    }
  },
  watch: {
    'value': {
      async handler(newValue) {
        if (!this.deptInit) { // 初次进入，防止数据未返回造成回显不正确
          await this.loadData()
        }
        if (this.value instanceof Array || this.attrs.multiple) { // 处理数据格式为tree 多选需要的格式[{lable:'部门',value:"bm-01"}]
          this.deptId = []
          const values = (this.value instanceof Array) ? newValue : newValue.split(',')
          values.forEach(item => {
            this.deptId.push({
              value: item,
              label: this.deptObj[item]?.deptName || item
            })
          })
        } else {
          this.deptId = {
            value: this.value,
            label: this.deptObj[this.value]?.deptName || this.value
          }
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    attrs() {
      return Object.assign(this.default, this.$attrs)
    }
  },
  methods: {
    loadData() {
      return deptEnableTree().then((res) => {
        if (res.success) {
          this.dataSource = res.result
          this.deptObj = this.getDeptObj(this.dataSource)
        } else {
          this.$message.warning(res.message)
        }
        this.deptInit = true
        this.loading = false
      })
    },
    handleChange(select, label, extra) {
      if (this.attrs.multiple) {
        const selectDept = []
        const deptId = []
        select.forEach(item => {
          deptId.push(item.value)
          selectDept.push(this.deptObj[item.value])
        })
        this.$emit('change', deptId.join(), selectDept)
      } else {
        const dataRef = extra.triggerNode.dataRef
        this.$emit('change', select.value, dataRef)
      }
    },
    getDeptObj(list) {
      let obj = {}
      list.forEach(item => {
        obj[item.deptCode] = { ...item }
        if (item.children && item.children.length > 0) {
          obj = Object.assign({}, obj, this.getDeptObj(item.children))
        }
      })
      return obj
    },
    getPopupContainerFn(node) {
      if (this.popupContainer === 'body') {
        return document.body
      } else if (this.popupContainer === 'parent') {
        return node.parentNode
      }
      return this.getPopupContainer(node)
    }
  },
  created() {
    this.loadData()
  }
}
</script>
